import pandas as pd
import random
import sys
import json
import redis
from redis.exceptions import RedisError, ConnectionError, AuthenticationError

def FACETS(network_path, flow_path, target_path, attack_target_path,source):

    performance_type = ['Fdelay', 'Fthroughput', 'Fjitter']
    Fdelay_per = {'1,2': [], '2,4': [], '8,11': []}
    Fthroughput_per = {'1,2': [], '2,4': [], '8,11': []}
    Fjitter_per = {'1,2': [], '2,4': [], '8,11': []}
    for i in range(100):
        for key in Fdelay_per.keys():
            Fdelay_per[key].append(random.uniform(0, 0.1))
            Fthroughput_per[key].append(random.uniform(5000, 9000))
            Fjitter_per[key].append(random.uniform(0, 0.1))

    # 连接 Redis by VainTale--statrt--
    r = redis.Redis(
        host='43.136.88.28',
        port=6379,
        db=4,
        password='147258369',
        decode_responses=True
    )

    # 模拟数据
    # 有可能某些DataFrame为空，模拟如下
    df_delay = pd.DataFrame(Fdelay_per)
    df_throughput = pd.DataFrame(Fthroughput_per)
    #df_jitter = pd.DataFrame(Fjitter_per)
    df_jitter = pd.DataFrame()  # 模拟Fjitter为空

    # 取所有df的最大长度，适应部分df为空的情况
    length = max(len(df) for df in [df_delay, df_throughput, df_jitter] if not df.empty)

    for idx in range(length):
        def get_row(df):
            if df.empty or idx >= len(df):
                return None  # 或 {}
            return df.iloc[idx].to_dict()
        valueGd = {
            'Fdelay': get_row(df_delay),
            'Fthroughput': get_row(df_throughput),
            'Fjitter': get_row(df_jitter)
        }
        valueXj = {
                    'Fdelay': get_row(df_delay),
                    'Fthroughput': get_row(df_throughput),
                    'Fjitter': get_row(df_jitter)
                }
        r.xadd("redis-stream-01", {
            "source": source,
            "index": idx + 1,
            "valueGd": json.dumps(valueGd, ensure_ascii=False),
            "valueXj": json.dumps(valueXj, ensure_ascii=False)
        })
        ## end##
            # 保持原有CSV输出功能
    pdFdelay_per = pd.DataFrame(Fdelay_per)
    pdFdelay_per.to_csv(target_path.format("Fdelay"), index=False)
    pdFthroughput_per = pd.DataFrame(Fthroughput_per)
    pdFthroughput_per.to_csv(target_path.format("Fthroughput"), index=False)
    pdFjitter_per = pd.DataFrame(Fjitter_per)
    pdFjitter_per.to_csv(target_path.format("Fjitter"), index=False)

if __name__ == '__main__':
    # 从命令行获取参数
    network_path = sys.argv[1]
    flow_path = sys.argv[2]
    target_path = sys.argv[3]
    attack_target_path = sys.argv[4]
    source = sys.argv[5]
    FACETS(network_path, flow_path, target_path, attack_target_path, source)  # 修改中文逗号为英文逗号
